package com.hjn.moredatasource.datasource.story.config;

import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * @author huaijn
 * @date 2021/12/6-16:49
 * @description 配置数据源配置类
 */
@Configuration
@MapperScan(basePackages = {"com/hjn/moredatasource/datasource/test/mapper"},
    sqlSessionFactoryRef = "storySqlSessionFactory")
public class StoryDatasourceConfig {

  /**
   * @user huaijiannan
   * @time 2021/12/6-16:52 从配置文件中，获取数据库的相关配置
   * @ConfigurationProperties : 读取配置文件
   */
  @Bean("storyDataSourceProperties")
  @ConfigurationProperties(prefix = "spring.datasource.test")
  public DataSourceProperties storyDataSourceProperties() {
    return new DataSourceProperties();
  }

  @Bean("storyDataSource")
  @Primary
  public DataSource storyDateSource(
      @Qualifier("storyDataSourceProperties") DataSourceProperties storyDataSourceProperties) {
    return storyDataSourceProperties.initializeDataSourceBuilder().build();
  }

  @Primary
  @Bean("storySqlSessionFactory")
  public SqlSessionFactory storySqlSessionFactory(DataSource dataSource) throws Exception {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource);
    // 设置mybatis的xml所在位置 ? 看看另一种实现方式
    sqlSessionFactoryBean.setMapperLocations(
        new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/test/*.xml"));
    return sqlSessionFactoryBean.getObject();
  }

  @Primary
  @Bean("storySqlSessionTemplate")
  public SqlSessionTemplate storySqlSessionTemplate(SqlSessionFactory storySqlSessionFactory) {
    return new SqlSessionTemplate(storySqlSessionFactory);
  }
}
